<template>
  <div class="home-page">
    <aside class="sidebar">
      <div class="search-box">
        <input type="text" v-model="searchQuery" placeholder="搜索组件...">
      </div>
      <div class="component-list">
        <div v-if="loading" class="loading">加载组件中...</div>
        <div v-else-if="filteredComponents.length === 0" class="no-results">
          未找到匹配的组件
        </div>
        <div 
          v-else
          v-for="component in filteredComponents" 
          :key="component.id"
          class="component-item"
          :class="{ active: selectedComponentId === component.id }"
          @click="selectComponent(component)"
        >
          <h3>{{ component.name }}</h3>
          <p>{{ component.description || '无描述' }}</p>
        </div>
      </div>
    </aside>
    
    <main class="content">
      <div v-if="!selectedComponent" class="welcome">
        <h1>欢迎使用 VueLens</h1>
        <p>从左侧选择一个组件查看详情</p>
      </div>
      <div v-else class="component-detail">
        <h1>
          {{ selectedComponent.name }}
          <span class="badge vue-version">Vue {{ selectedComponent.vueVersion }}</span>
        </h1>
        <p v-if="selectedComponent.description">{{ selectedComponent.description }}</p>
        
        <div class="info-grid">
          <div class="info-item">
            <strong>文件路径</strong>
            <span>{{ selectedComponent.filePath }}</span>
          </div>
          <div class="info-item">
            <strong>最后更新</strong>
            <span>{{ formatDate(selectedComponent.updatedAt) }}</span>
          </div>
        </div>
        
        <!-- Props部分 -->
        <div v-if="selectedComponent.props && selectedComponent.props.length > 0" class="section">
          <h2>Props</h2>
          <table>
            <thead>
              <tr>
                <th>名称</th>
                <th>类型</th>
                <th>默认值</th>
                <th>必填</th>
                <th>描述</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="prop in selectedComponent.props" :key="prop.name">
                <td><code>{{ prop.name }}</code></td>
                <td><code>{{ prop.type }}</code></td>
                <td>{{ prop.defaultValue !== undefined ? prop.defaultValue : '-' }}</td>
                <td>{{ prop.required ? '是' : '否' }}</td>
                <td>{{ prop.description || '-' }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <!-- Events部分 -->
        <div v-if="selectedComponent.events && selectedComponent.events.length > 0" class="section">
          <h2>Events</h2>
          <div class="event-item" v-for="event in selectedComponent.events" :key="event.name">
            <h3><code>{{ event.name }}</code></h3>
            <p v-if="event.description">{{ event.description }}</p>
            
            <table v-if="event.arguments && event.arguments.length > 0">
              <thead>
                <tr>
                  <th>参数</th>
                  <th>类型</th>
                  <th>描述</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="arg in event.arguments" :key="arg.name">
                  <td><code>{{ arg.name }}</code></td>
                  <td><code>{{ arg.type }}</code></td>
                  <td>{{ arg.description || '-' }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        
        <!-- Slots部分 -->
        <div v-if="selectedComponent.slots && selectedComponent.slots.length > 0" class="section">
          <h2>Slots</h2>
          <div class="slot-item" v-for="slot in selectedComponent.slots" :key="slot.name">
            <h3><code>{{ slot.name || 'default' }}</code></h3>
            <p v-if="slot.description">{{ slot.description }}</p>
            
            <table v-if="slot.bindings && slot.bindings.length > 0">
              <thead>
                <tr>
                  <th>绑定名</th>
                  <th>类型</th>
                  <th>描述</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="binding in slot.bindings" :key="binding.name">
                  <td><code>{{ binding.name }}</code></td>
                  <td><code>{{ binding.type }}</code></td>
                  <td>{{ binding.description || '-' }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        
        <!-- Methods部分 -->
        <div v-if="selectedComponent.methods && selectedComponent.methods.length > 0" class="section">
          <h2>Methods</h2>
          <div class="method-item" v-for="method in selectedComponent.methods" :key="method.name">
            <h3><code>{{ method.name }}({{ formatParams(method.params) }})</code></h3>
            <p v-if="method.description">{{ method.description }}</p>
            
            <table v-if="method.params && method.params.length > 0">
              <thead>
                <tr>
                  <th>参数</th>
                  <th>类型</th>
                  <th>描述</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="param in method.params" :key="param.name">
                  <td><code>{{ param.name }}</code></td>
                  <td><code>{{ param.type }}</code></td>
                  <td>{{ param.description || '-' }}</td>
                </tr>
              </tbody>
            </table>
            
            <div v-if="method.returns">
              <strong>返回: </strong>
              <code>{{ method.returns.type }}</code>
              <span v-if="method.returns.description"> - {{ method.returns.description }}</span>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';

interface ComponentProp {
  name: string;
  type: string;
  description: string;
  defaultValue?: string;
  required: boolean;
  values?: string[];
}

interface ComponentEventArgument {
  name: string;
  type: string;
  description: string;
}

interface ComponentEvent {
  name: string;
  description: string;
  arguments: ComponentEventArgument[];
}

interface ComponentSlotBinding {
  name: string;
  type: string;
  description: string;
}

interface ComponentSlot {
  name: string;
  description: string;
  bindings: ComponentSlotBinding[];
}

interface ComponentMethodParam {
  name: string;
  type: string;
  description: string;
}

interface ComponentMethodReturn {
  type: string;
  description: string;
}

interface ComponentMethod {
  name: string;
  description: string;
  params: ComponentMethodParam[];
  returns?: ComponentMethodReturn;
}

interface Component {
  id: string;
  encodedId: string;
  name: string;
  description: string;
  filePath: string;
  props: ComponentProp[];
  events: ComponentEvent[];
  slots: ComponentSlot[];
  methods: ComponentMethod[];
  createdAt: string;
  updatedAt: string;
  vueVersion: string;
}

export default defineComponent({
  name: 'Home',
  setup() {
    const components = ref<Component[]>([]);
    const loading = ref(true);
    const searchQuery = ref('');
    const selectedComponentId = ref<string | null>(null);
    const selectedComponent = ref<Component | null>(null);
    const webSocket = ref<WebSocket | null>(null);
    const router = useRouter();

    const filteredComponents = computed(() => {
      if (!searchQuery.value) {
        return components.value;
      }

      const query = searchQuery.value.toLowerCase();
      return components.value.filter(component => 
        component.name.toLowerCase().includes(query) ||
        component.description.toLowerCase().includes(query) ||
        component.filePath.toLowerCase().includes(query)
      );
    });

    // 连接WebSocket
    const connectWebSocket = () => {
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
      webSocket.value = new WebSocket(`${protocol}//${window.location.host}/ws`);
      
      webSocket.value.onopen = () => {
        console.log('WebSocket连接已建立');
      };
      
      webSocket.value.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          if (data.type === 'components-updated') {
            // 当收到组件更新消息时，重新加载组件
            fetchComponents();
          }
        } catch (error) {
          console.error('解析WebSocket消息失败:', error);
        }
      };
      
      webSocket.value.onclose = () => {
        console.log('WebSocket连接已关闭');
        // 尝试重新连接
        setTimeout(connectWebSocket, 5000);
      };
      
      webSocket.value.onerror = (error) => {
        console.error('WebSocket错误:', error);
      };
    };

    // 获取组件列表
    const fetchComponents = async () => {
      try {
        loading.value = true;
        const response = await fetch('/api/components');
        const data = await response.json();
        components.value = data;
        
        // 如果有选中的组件，更新其数据
        if (selectedComponentId.value) {
          const component = components.value.find(comp => comp.id === selectedComponentId.value);
          if (component) {
            selectedComponent.value = component;
          }
        }
      } catch (error) {
        console.error('获取组件列表失败:', error);
      } finally {
        loading.value = false;
      }
    };

    // 选择组件
    const selectComponent = (component: Component) => {
      selectedComponentId.value = component.id;
      selectedComponent.value = component;
    };

    // 格式化日期
    const formatDate = (dateStr: string) => {
      try {
        const date = new Date(dateStr);
        return date.toLocaleString();
      } catch (e) {
        return dateStr;
      }
    };

    // 格式化方法参数
    const formatParams = (params: ComponentMethodParam[]) => {
      if (!params || !params.length) return '';
      return params.map(param => param.name).join(', ');
    };

    onMounted(async () => {
      await fetchComponents();
      connectWebSocket();
    });

    return {
      components,
      loading,
      searchQuery,
      selectedComponentId,
      selectedComponent,
      filteredComponents,
      selectComponent,
      formatDate,
      formatParams
    };
  }
});
</script>

<style lang="scss" scoped>
.home-page {
  display: flex;
  flex: 1;
  height: 100%;
}

.slot-item,
.method-item {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--color-border);
  
  h3 {
    font-size: 18px;
    margin-bottom: 8px;
    color: var(--color-secondary);
  }
}

.no-results {
  text-align: center;
  padding: 20px;
  color: var(--color-text-light);
}
</style> 